import { UpFile, toFileModel } from "../components/Upfile";
import { Input, Form, Button, Radio, InputNumber, Spin } from "antd";
import { TagList } from "../components/TagList";
import { useNavigate, useParams } from "react-router-dom";
import { request, ResBody } from "../common/request";
import { useAsync } from "react-use";
import { useAuthStore } from "../store/auth";
import { useState } from "react";
import { useSystemStore } from "../store/system";

const Publish: React.FC = () => {
  const [form] = Form.useForm();
  const plan = Form.useWatch("plan", form);
  const navigate = useNavigate();
  const { gid } = useParams();
  const auth = useAuthStore();
  const system = useSystemStore();
  const [loading, setLoading] = useState(false);

  useAsync(async () => {
    if (gid) {
      setLoading(true);
      const ret = await request.get<any, ResBody>(`/api/goods/edit/${gid}`);
      if (ret.code === 200) {
        form.setFieldsValue(ret.goods);
      }
      setLoading(false);
    } else {
      form.setFieldsValue({
        preview: [],
        intro: "",
        tags: [],
        plan: "free",
        price: "1.00",
        status: "public",
      });
    }
  }, [gid]);

  const onFinish = async (values: any) => {
    console.log(values);
    let data = form.getFieldsValue();
    //过滤file对象
    data = {
      ...data,
      files: toFileModel(data.files),
      preview: toFileModel(data.preview),
      id: gid,
    };
    // console.log(data);
    setLoading(true);

    let url = gid ? `/api/goods/update/${gid}` : "/api/goods/create";
    const ret = await request.post<any, ResBody>(url, data);

    if (ret?.code === 200) {
      system.message("success", gid ? "修改成功" : "创建成功");
      navigate(`/u/${auth.user?.account}`);
    }
    setLoading(false);
  };

  return (
    <Spin spinning={loading}>
      <div className="max-w-xl">
        <Form onFinish={onFinish} form={form}>
          <Form.Item name="preview">
            <UpFile type="picture-card" label="上传预览" maxCount={10} />
          </Form.Item>
          <Form.Item
            name="title"
            rules={[{ required: true, message: "请填写标题" }]}
          >
            <Input
              placeholder="填写标题"
              size="large"
              maxLength={28}
              showCount
            />
          </Form.Item>
          <Form.Item name="intro">
            <Input.TextArea
              placeholder="内容"
              size="large"
              showCount
              maxLength={1000}
              autoSize={{ minRows: 4, maxRows: 10 }}
            />
          </Form.Item>
          <Form.Item name="tags" label="标签">
            <TagList />
          </Form.Item>
          <Form.Item
            name="files"
            rules={[{ required: true, message: "请上传文件" }]}
          >
            <UpFile type="text" label="交付文件" />
          </Form.Item>
          <div className="flex space-x-2 items-center mb-3">
            <Form.Item name={"plan"} noStyle>
              <Radio.Group className="flex space-x-2 items-center text-xl">
                <label className="btn-radio">
                  <Radio value="free">免费</Radio>
                </label>
                <label className="btn-radio">
                  <Radio value="buy">一口价</Radio>
                </label>
              </Radio.Group>
            </Form.Item>
            {plan === "buy" && (
              <div className="text-xl font-bold">
                <span className="ml-2">¥：</span>
                <Form.Item noStyle name="price">
                  <InputNumber
                    size="large"
                    precision={2}
                    className="max-w-[100px]"
                  />
                </Form.Item>{" "}
                元
              </div>
            )}
          </div>
          <Form.Item name="status">
            <Radio.Group className="flex space-x-2 items-center text-xl">
              <Radio value="public">公开</Radio>
              <Radio value="private">仅自己可见</Radio>
            </Radio.Group>
          </Form.Item>
          <Button block size="large" type="primary" htmlType="submit">
            提交
          </Button>
        </Form>
      </div>
    </Spin>
  );
};

export default Publish;
